/**
* COPYRIGHT. whx. ALL RIGHTS RESERVED.
* Project: just-http
* Author: whx <harrywu304@gmail.com>
* Create On: Dec 2, 2011 7:42:10 PM
*/

package org.justframework.plugin.http;

import javax.servlet.http.HttpServletRequest;

/**
 *
 */
public class HttpIPUtil {
	/**
	 * 获取最接近的客户端IP
	 */
	public static String getNearestClientIP(HttpServletRequest request){
		return getClientIP(request, 1);
	}
	
	/**
	 * 获取用户终端的IP地址
	 * @param request http请求
	 * @return 用户终端的IP地址
	 */
	public static String getClientIP(HttpServletRequest request) {
		return getClientIP(request,0);
	}
	
	/**
	 * 根据指定模式获取客户端IP
	 * @param request http请求
	 * @param mode 0:user ip, 1: nearest client ip
	 * @return
	 */
	private static String getClientIP(HttpServletRequest request, int mode){
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}else{
			String[] ips = ip.split(",");
            if (ips.length > 0) {
				switch(mode){
				case 0:
					//user ip, the first ip from left
					ip = ips[0].trim();
                    return ip;
				case 1:
					//nearest client ip, the first ip from right
					ip = ips[ips.length - 1].trim();
                    return ip;
				}
				ip = null ;
			}
		}

		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}else{
			return ip.trim();
		}

		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip.trim();
	}
}
